package com.cheyun.netsalev3.widget

import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.EditText
import com.cheyun.netsalev3.R

/**
 * 带清空按钮的Editview
 */
class MyEditText : EditText {

    private var mClearDrawable: Drawable? = null

    constructor(context: Context) : super(context) {}


    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.myEditText)
        mClearDrawable = a.getDrawable(R.styleable.myEditText_delete_right)
        a.recycle()
        init()
    }

    private fun init() {
        if (mClearDrawable == null)
            mClearDrawable = resources.getDrawable(R.drawable.b01_1_qklb_ssjm_x, null)
    }

    override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        text?.apply {
            setClearIconVisible(hasFocus() && text.isNotEmpty())
        }

    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        setClearIconVisible(focused && length() > 0)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_UP -> {
                val drawable = compoundDrawables[DRAWABLE_RIGHT]
                if (drawable != null && event.x <= width - paddingRight
                        && event.x >= width - paddingRight - drawable.bounds.width()) {
                    setText("")
                }
            }
        }
        return super.onTouchEvent(event)
    }

    private fun setClearIconVisible(visible: Boolean) {
        setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[DRAWABLE_LEFT], compoundDrawables[DRAWABLE_TOP],
                if (visible) mClearDrawable else null, compoundDrawables[DRAWABLE_BOTTOM])
    }

    companion object {
        private const val DRAWABLE_LEFT = 0
        private const val DRAWABLE_TOP = 1
        private const val DRAWABLE_RIGHT = 2
        private const val DRAWABLE_BOTTOM = 3
    }

}